package com.briup.corejava.day19;

import com.briup.corejava.day11.pojo.Student;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 使用对象流和文件流读取a.txt中的数据
 * 并遍历集合
 *
 * 序列化接口 Serializable
 * 序列化id SerialVersionUID：保证类的结构发生改变，序列化id不变，也可以正常反序列化
 */
public class Test2_or {
    public static void main(String[] args) {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        File file = new File("src/com/briup/corejava/day19/file/a.txt");

        try {
            fis = new FileInputStream(file);
            ois = new ObjectInputStream(fis);
            // 读取对象
            Object o = ois.readObject();
            // o如何安全转换为List<Student>
            // 准备一个集合来接受数据
            List<Student> list = new ArrayList<>();
            if(o instanceof List){
                List<?> l = (List<?>) o;
                for(Object obj : l){
                    if(obj instanceof Student){
                        Student s = (Student) obj;
                        list.add(s);
                    }
                }
            }
            list.forEach(System.out::println);

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
